import { Buffer } from 'buffer';
import * as iconv from 'iconv-lite';
import * as icu from 'icu-uchar';

export class TextProcessor {
    private static ENCODINGS = ['utf8', 'gb18030', 'big5', 'shiftjis'];
    private static LINE_BREAKS = /\r\n|\n|\r/g;

    static detectEncoding(buffer: Buffer): string {
        // 简单的BOM检测
        if (buffer.length >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
            return 'utf8';
        }
        
        // 使用启发式方法检测中文编码
        const sample = buffer.slice(0, 1000).toString('binary');
        if (/[\x80-\xFF]/.test(sample)) {
            return sample.includes('¥') ? 'gb18030' : 'big5';
        }
        
        return 'utf8';
    }

    static normalizeText(input: string | Buffer): string {
        const buffer = Buffer.isBuffer(input) ? input : Buffer.from(input);
        const encoding = this.detectEncoding(buffer);
        let text = iconv.decode(buffer, encoding);

        // 统一换行符
        text = text.replace(this.LINE_BREAKS, '\n');

        // 全角/半角转换
        text = icu.transform(text, 'Fullwidth-Halfwidth');

        // 添加文本方向标记
        const isCJK = /[\u4E00-\u9FFF\u3040-\u30FF\uAC00-\uD7AF]/.test(text);
        return isCJK ? `\u202B${text}\u202C` : text;
    }

    static processLayout(text: string): string {
        // 中英文间距处理
        return text.replace(/([a-zA-Z])([\u4e00-\u9fa5])/g, '$1 $2')
                  .replace(/([\u4e00-\u9fa5])([a-zA-Z])/g, '$1 $2');
    }
}